const mongoose = require('mongoose');

const documentGenerationSchema = new mongoose.Schema({
  projectId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Project',
    required: true
  },
  projectVersion: String,
  generatedBy: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  generateTime: {
    type: Date,
    default: Date.now
  },
  status: {
    type: String,
    enum: ['pending', 'processing', 'success', 'failed'],
    default: 'pending'
  },
  format: {
    type: String,
    enum: ['docx', 'pdf'],
    default: 'docx'
  },
  fileName: String,
  fileUrl: String,
  fileSize: Number,
  configSnapshot: {
    projectConfig: Object,
    sectionsConfig: [Object],
    formsConfig: [Object]
  },
  generateOptions: {
    includeEmptyFields: {
      type: Boolean,
      default: false
    },
    format: String,
    template: String
  },
  error: String,
  processingTime: Number
}, {
  timestamps: false
});

// 索引
documentGenerationSchema.index({ projectId: 1, generateTime: -1 });
documentGenerationSchema.index({ generatedBy: 1, generateTime: -1 });
documentGenerationSchema.index({ status: 1 });
documentGenerationSchema.index({ projectId: 1, status: 1, generateTime: -1 });

module.exports = mongoose.model('DocumentGeneration', documentGenerationSchema);